const App = getApp()

Page({
	data: {
		show: !0,
		form: {},
		msg: {
			miles: '请输入行驶里程',
			linkman: '请输入联系人',
			phone: '请输入联系电话'
		},
	},
	onLoad (option) {
		this.setData({ id: option.id, carInfo: option.carInfo })
	},
	onShow () {
		wx.showNavigationBarLoading()
		this.carDetail(this.data.id, () => {
      wx.hideNavigationBarLoading()
    })
	},
	carDetail (id, cb) { // 获取车辆详情
		App.HttpService.carDetail({id: id}).then(res => {
			cb && cb()
			const data = res.data
			if (data.code == 200) {
				this.setData({form: data.data})
			} else {
				wx.showToast({
					title: data.msg,
					image: '../../../assets/images/warning.png',
					duration: 1500
				})
			}
		})
	},
	inputBlur (e) { // 失去焦点事件
		let form = this.data.form
		let { key } = e.currentTarget.dataset
		let { value } = e.detail
		for (var i in form) {
			if (i == key) {
				this.setData({ ['form.' + key]: value })
			}
		}
	},
	submitForm () {
		let { id, form, msg} = this.data
		for (var i in form) {
			if (form[i] === '') {
				wx.showToast({
					title: msg[i],
					image: '../../../assets/images/warning.png',
					duration: 1500
				})
				return false
			}
		}
		App.HttpService.carSave(form).then(res => {
			const data = res.data
			if (data.code == 200) {
				this.showToast('修改成功')
			} else {
				wx.showToast({
					title: data.msg,
					image: '../../../assets/images/warning.png',
					duration: 1500
				})
			}
		})
	},
	showToast (message) {
		wx.showToast({
			title: message, 
			icon: 'success', 
			duration: 1500,
			success: () => {
				let pages = getCurrentPages()
				if (pages.length > 1) {
					let prePage = pages[pages.length - 2]
					prePage.onLoad()
				}
				wx.navigateBack({ delta: 1 }) // 返回上一页
			}
		})
	}
})